import { baseURL } from './config'
import axios from 'axios'
class HttpRequest {
  constructor(baseUrl = baseURL) {
    this.baseUrl = baseUrl;
    this.queue = {}
  }
  //内置配置
  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      headers: {

      }
    }
    return config;
  }
  //天添加拦截器
  interceptors(instance, url) {
    instance.interceptors.request.use(config => {
      //添加全局的loading
      console.log('interceptors.request', config);
      if (!Object.keys(this.queue).length) {
        //loading展示loading.show()
        console.log('展示loading');
      }
      this.queue[url] = true;
      return config;
    }, error => {
      return Promise.reject(error)
    })

    instance.interceptors.response.use(res => {
      console.log('interceptors.response', res);
      delete this.queue[url];
      //筛选结果
      const { data, status } = res;
      return { data, status };
    }, error => {
      delete this.queue[url];
      return Promise.reject(error)
    })
  }
  request(options) {
    console.log('options',options);
    if((options.method=='get'||!options.method)&&!options.params){
      options.params=options.data;
      delete options.data;
    }

    const instance = axios.create();
    options = Object.assign(this.getInsideConfig(), options);
    this.interceptors(instance, options.url);
    return instance(options)
  }
}

const https = new HttpRequest()

export default https;
